#include "stdafx.h"
#include "ServerObjectManager.h"

#include "..\common\CommonUtil.h"

object_manager::object_manager(void)
: m_bRepeating(false) {
	InitializeCriticalSection(&m_CriticalSection);	
}

object_manager::~object_manager(void) {
	DeleteCriticalSection(&m_CriticalSection);
}

void object_manager::StartRepeat(void) {
	assert(m_bRepeating == false);

	EnterCriticalSection(&m_CriticalSection);
	// Leave called by EndRepate.
	m_bRepeating = true;
	m_Repeator = m_ObjectInfoList.begin();
}

void object_manager::EndRepeat(void) {
	assert(m_bRepeating == true);	

	m_bRepeating = false;
	LeaveCriticalSection(&m_CriticalSection);
	// Enter called by Start Repeat
}

void object_manager::NextRepeat(void) {
	assert(m_bRepeating == true);
	assert(m_Repeator != m_ObjectInfoList.end());

	++m_Repeator;
}

object_manager::object_info* object_manager::Repeat(void) {
	assert(m_bRepeating == true);

	if(m_Repeator != m_ObjectInfoList.end())
		return &(*m_Repeator);
	else
		return NULL;
}

int object_manager::GetObjectCount(void) {	
	cs_auto cs(&m_CriticalSection);

	return m_ObjectInfoList.size();
};

unsigned int object_manager::NewObject(OBJECT_TYPE ObjectType, unsigned int OwnerCode, int ExtraLength, char* ObjectExtraData) {
	cs_auto cs(&m_CriticalSection);

	object_info AddInfo;
	AddInfo.ObjectID			= GenerateObjectID();
	AddInfo.ObjectType			= ObjectType;
	AddInfo.ObjectOwnerCode		= OwnerCode;
	AddInfo.ObjectExtraLength	= ExtraLength;
	AddInfo.ObjectExtraData		= new char[ExtraLength];
								  memcpy(AddInfo.ObjectExtraData, ObjectExtraData, ExtraLength);

	m_ObjectInfoList.push_back(AddInfo);

	return AddInfo.ObjectID;
}

bool object_manager::DeleteObject(unsigned int ObjectID) {
	bool Result = false;

	// repeat example..
	
	for(StartRepeat();	 Repeat() != NULL;	NextRepeat()) 
		if(Repeat()->ObjectID == ObjectID)
			break;

	if(Repeat() != NULL) {
		delete [] Repeat()->ObjectExtraData;
		m_ObjectInfoList.erase(m_Repeator);
		Result = true;
	}
	EndRepeat();

	return Result;
}

unsigned int object_manager::GenerateObjectID(void) {
	static int IDSeed = rand() % 100;
	// start id is difference.

	return IDSeed++;
}